package com.woniuxy.yoga.order.service.job;

import com.alibaba.fastjson.JSONObject;
import com.woniuxy.yoga.commons.core.model.Result;
import com.woniuxy.yoga.commons.core.statedata.OrderState;
import com.woniuxy.yoga.order.client.EvaluateClient;
import com.woniuxy.yoga.order.dao.mapper.OrderInfoMapper;
import com.woniuxy.yoga.order.dao.model.OrderInfo;
import com.woniuxy.yoga.order.model.exception.OrderException;
import com.woniuxy.yoga.order.model.form.AddServiceEvaluationForm;
import com.xxl.job.core.context.XxlJobHelper;
import com.xxl.job.core.handler.annotation.XxlJob;
import io.seata.spring.annotation.GlobalTransactional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Map;
import java.util.Objects;

@Component
public class OrderExpire {

    @Autowired
    private OrderInfoMapper orderInfoMapper;

    @Autowired
    private EvaluateClient evaluateClient;

    @XxlJob("orderExpire")
    @GlobalTransactional(rollbackFor = Exception.class)
    public void orderEvaluateExpire(){
        System.out.println("超时未评价，系统默认好评");
        String jobParam = XxlJobHelper.getJobParam();
        JSONObject jsonObject = JSONObject.parseObject(jobParam);
        Map<String, Object> map = JSONObject.toJavaObject(jsonObject, Map.class);
        //获取订单id
        String orderNum = map.get("orderNum").toString();
        OrderInfo orderInfo = orderInfoMapper.selectById(orderNum);
        //条件筛选
        if (orderInfo!=null && Objects.equals(orderInfo.getOrderState(), OrderState.ORDER_STATE_PAYED)){
            if (Objects.equals(orderInfo.getOrderEvaluationState(), OrderState.ORDER_EVALUATION_STATE_NO)){
                //用户未评价，系统默认好评
                AddServiceEvaluationForm form = new AddServiceEvaluationForm();
                form.setOrderNum(orderNum);
                form.setComment("用户未作出评论，已默认好评");
                form.setRating(5);
                Result<String> result = evaluateClient.addServiceEvaluationAuto(form);
                if (result.getCode()!=200) throw new OrderException(result.getCode(),result.getMessage());
                //修改订单评价状态
                orderInfo.setOrderEvaluationState(OrderState.ORDER_EVALUATION_STATE_YES);
                orderInfoMapper.updateById(orderInfo);
            }
        }
    }
}
